package com.shopping.service.impl;


import com.alibaba.druid.sql.visitor.functions.If;
import com.shopping.mapper.BookMapper;
import com.shopping.model.Car;
import com.shopping.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class CarServiceImpl implements CarService {
    private RedisTemplate redisTemplate;
    private HashOperations hashOperations;
    private BookMapper bookMapper;

    //构造器注入RedisTemplate，并且序列化
    @Autowired
    public CarServiceImpl(RedisTemplate redisTemplate, BookMapper bookMapper) {
        this.redisTemplate = redisTemplate;
        this.bookMapper = bookMapper;
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //获得Redis对象
        hashOperations = redisTemplate.opsForHash();
    }


    /*
     * 版本1
     */
    /*
    @Override
    public void addCar(Car car) throws Exception {
        //向Redis中添加一个商品
        List<Car> cars = new ArrayList<>();
        //设置合计
        car.setTotal(car.getCar_count()*car.getBook_price());
        cars.add(car);
        //向Redis中添加购物车信息
        hashOperations.put("cars", "user:" + car.getUser_id(), cars);
    }*/

    /**
     * 版本2:添加多个商品
     *
     * @param car
     * @throws Exception
     */
    /*
    @Override
    public void addCar(Car car) throws Exception {
        List<Car> carList;
        //是否存在购物车
        Boolean bool = redisTemplate.hasKey("cars");
        if (bool) {//购物车存在
            //获取redis中的数据
            carList = (List<Car>) hashOperations.get("cars", "user:" + car.getUser_id());
            Boolean exists = false;//redis是否存在新要添加的商品，默认不存在
            for (Car car1 : carList) {
                if (car1.getBook_id().equals(car.getBook_id())) {//判断redis是否存在新添加的商品
                    //如果存在数量则增加
                    car1.setCar_count(car1.getCar_count() + car.getCar_count());
                    //更新总价格
                    car1.setTotal(car1.getCar_count() * car1.getBook_price());
                    exists = true;
                    break;
                }
            }
            if (!exists) {//如果不存在商品
                car.setTotal(car.getCar_count() * car.getBook_price());
                //直接添加新商品
                carList.add(car);
            }
        } else {//不存在购物车
            //创建购物车集合
            carList = new ArrayList<>();
            car.setTotal(car.getCar_count() * car.getBook_price());
            carList.add(car);
        }
        hashOperations.put("cars", "user:" + car.getUser_id(), carList);
    }
*/

    /**
     * 版本3:使用Map解存储购物车内信息
     * @param car
     * @throws Exception
     */
    @Override
    public void addCar(Car car) throws Exception {
        //声明Map集合存储购物车信息
        Map<Integer, Car> carMap = null;
        //是否存在购物车
        Boolean bool = redisTemplate.hasKey("cars");
        if (bool) {//购物车存在
            //获取redis中的数据
            carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + car.getUser_id());
            //判断当前用户购物车是否存在
            if (carMap == null) {//如果不存在创建Map对象
                carMap = new HashMap<>();

            } else {//当前用户购物车存在
                //判断当前商品是否在购物车
                if (carMap.containsKey(car.getBook_id())) {
                    //更新数量
                    Car updateCar = carMap.get(car.getBook_id());
                    updateCar.setCar_count(updateCar.getCar_count() + car.getCar_count());
                } else {//当前商品不存在
                    //直接加入map集合
                    carMap.put(car.getBook_id(), car);
                }
            }
        } else {//当前购物车不存在
            carMap = new HashMap<>();
            carMap.put(car.getBook_id(), car);
        }
        hashOperations.put("cars", "user:" + car.getUser_id(), carMap);
    }

    @Override
    public List<Car> queryCarInfo(int user_id) {
        Map<Integer, Car> carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + user_id);
        if (carMap == null) {
            return null;
        }
        List<Car> carList =new ArrayList<>();
        Collection<Car> carInfo = carMap.values();
        carList.addAll(carInfo);
        return carList;
    }

    @Override
    public Car getCarInfoById(int user_id, int book_id) {
        //得到对应用户的购物车
        Map<Integer, Car> carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + user_id);

        return carMap.get(book_id);
    }

    @Override
    public void updateCarCount(Car car) {
        //获取当前用户购物车
        Map<Integer, Car> carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + car.getUser_id());
        if (carMap.containsKey(car.getBook_id())){//存在该书
            Car updateCar = carMap.get(car.getBook_id());
            updateCar.setCar_count(car.getCar_count());
            carMap.put(updateCar.getBook_id(),updateCar);
        }
        //修改redis中数据
        hashOperations.put("cars", "user:" + car.getUser_id(), carMap);
    }

    @Override
    public void delCarByBookId(int user_id, Integer book_id) {
        Map<Integer, Car> carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + user_id);

        if (carMap.containsKey(book_id)){//购物车是否存在该书，存在即删除
                carMap.remove(book_id);
        }
        //修改redis中数据
        hashOperations.put("cars", "user:" + user_id, carMap);
    }

    @Override
    public Integer getCarCount(Integer user_id) {
        //redis获取当前购物车
        Map<Integer, Car> carMap = (Map<Integer, Car>) hashOperations.get("cars", "user:" + user_id);

        return carMap.size();
    }
    /*
    @Override
    public List<CarView> queryCarInfo(int user_id) {
        //从redis中获取去购物车信息
        List<Car> carList = (List<Car>) hashOperations.get("cars", "user:" + user_id);
        //将carList中的book_id封装到list集合中
        List<Integer> bookIdList = new ArrayList<>();
        for (Car car : carList) {
            bookIdList.add(car.getBook_id());
        }
        //根据book_id获得对应商品数据
        List<Book> books = bookMapper.queryBookById(bookIdList.toArray(new Integer[bookIdList.size()]));
        List<CarView> carViewList = new ArrayList<>();
        for (Car car : carList) {
            CarView carView = new CarView();
            //购买数量
            carView.setCar_count(car.getCar_count());
            carView.setBook_id(car.getBook_id());
            //获得商品数据
            for (Book book : books) {
                if (book.getBook_id().equals(car.getBook_id())) {
                     carView.setBook_image(book.getBook_image());
                     carView.setBook_name(book.getBook_name());
                     carView.setBook_price(book.getBook_price());
                     carView.setTotal(car.getCar_count()*book.getBook_price());
                     break;
                }
            }
            carViewList.add(carView);
        }

        return carViewList;
    }*/
}
